<template>
  <div>
    <!-- 内容区域 -->
    <el-card class="box-card">
      <!-- 标题区域 -->
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="obj in cateList" :key="obj.id" :label="obj.cate_name" :value="obj.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left:15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="choseFn">筛选</el-button>
            <el-button type="info" size="small" @click="resetFn">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="showPubDialogFn">发表文章</el-button>
      </div>
      <!-- 文章表格区域 -->
      <el-table :data="artList" border style="width: 100%" stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="scope">
            <el-link type="primary" @click="showDetailFn(scope.row.id)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类" width="180">
        </el-table-column>
        <el-table-column prop="pub_date" label="发表时间">
          <template v-slot="scope">
            <span>{{ $formatDate(scope.row.pub_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="removeFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChangeFn" @current-change="handleCurrentChangeFn"
        :current-page.sync="q.pagenum" :page-sizes="[2, 3, 5, 10]" :page-size.sync="q.pagesize"
        layout="total,sizes,prev,pager,next,jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 发表文章的对话框 -->
    <el-dialog title="发表文章" :visible.sync="pubDialogVisible" fullscreen :before-close="handleClose"
      @close="dialogCloseFn">
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width:100%;">
            <el-option v-for="obj in cateList" :key="obj.id" :label="obj.cate_name" :value="obj.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor v-model="pubForm.content" @blur="contentChangeFn"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <img src="../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef">
          <br>
          <input type="file" style="display:none" accept="image/*" ref="iptFileRef" @change="changeCoverFn">
          <el-button type="text" @click="selCoverFn">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticleFn('已发布')">发布</el-button>
          <el-button type="info" @click="pubArticleFn('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>
      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ $formatDate(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <!-- 文章的封面 -->
      <img v-if="artDetail.cover_img" alt="" :src="baseURL + artDetail.cover_img">
      <!-- 文章的详情 -->
      <div class="detail-box" v-html="artDetail.content"></div>
    </el-dialog>
  </div>
</template>

<script>
import { getArtCateListAPI, getArtListAPI, delArticleAPI, uploadArticleAPI, getArtDetailAPI } from '@/api/index.js'
import imgObj from '../../assets/images/cover.jpg'
import { baseURL } from '@/utils/request.js'
export default {
  name: 'my-artList',
  data() {
    return {
      baseURL,
      q: {
        pagenum: 1,
        pagesize: 5,
        cate_id: null,
        state: null
      },
      // 保存文章的分类
      cateList: [],
      // 文章列表
      artList: [],
      // 文章总数
      total: 0,
      // 控制发表文章页面的出现
      pubDialogVisible: false,
      pubForm: {
        // 文章标题
        title: '',
        // 文章分类
        cate_id: '',
        // 文章内容
        content: '',
        // 文章封面
        cover_img: null,
        // 文章状态
        state: ''
      },
      // 发布文章-表单的验证规则对象
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章分类', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        cover_img: [
          // 这里的图片校验和前面的富文本器校验一样的解决方法（单独校验）
          { required: true, message: '请选择封面', trigger: 'blur' }
        ]
      },
      // 用于查看文章详情的对话框
      detailVisible: false,
      // 文章详情
      artDetail: {}
    }
  },
  created() {
    // 请求分类的数据
    this.getCateFn()
    // 请求文章列表
    this.getArticleListFn()
  },
  methods: {
    // 获取所有分类
    async getCateFn() {
      const { data: res } = await getArtCateListAPI()
      console.log('res', res)
      this.cateList = res.data
    },
    // 获取文章列表
    async getArticleListFn() {
      const { data: res } = await getArtListAPI(this.q)
      this.artList = res.data
      this.total = res.total
    },
    // 发表文章的按钮
    showPubDialogFn() {
      this.pubDialogVisible = true
    },
    // 筛选按钮
    choseFn() {
      this.q.pagenum = 1
      this.q.pagesize = 2
      this.getArticleListFn()
    },
    // 重置按钮
    resetFn() {
      this.q.pagenum = 1
      this.q.pagesize = 2
      this.q.cate_id = null
      this.q.state = null
      this.getArticleListFn()
    },
    // 删除文章的按钮
    async removeFn(artId) {
      const { data: res } = await delArticleAPI(artId)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      if (this.artList.length === 1) {
        if (this.q.pagenum > 1) {
          this.q.pagenum--
        }
      }
      this.getArticleListFn()
    },
    // 分页->每页条数改变触发
    handleSizeChangeFn(sizes) {
      this.q.pagesize = sizes
      this.q.pagenum = 1
      this.getArticleListFn()
    },
    // 当前页码改变时触发
    handleCurrentChangeFn(nowPage) {
      this.q.pagenum = nowPage
      this.getArticleListFn()
    },
    // 关闭写文章的页面时 弹出提示框
    async handleClose(done) {
      // 询问是否确认关闭对话框
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 取消了关闭阻止住 什么都不干
      if (confirmResult === 'cancel') return
      done()
    },
    // 写文章的页面关闭时 清空表单
    dialogCloseFn() {
      this.$refs.pubFormRef.resetFields()
      this.$refs.imgRef.setAttribute('src', imgObj)
    },
    // 富文本编辑器内容改变触发此事件方法
    contentChangeFn() {
      this.$refs.pubFormRef.validateField('content')
    },
    // 选择封面
    selCoverFn() {
      this.$refs.iptFileRef.click()
    },
    // 用户选择了封面文件
    changeCoverFn(e) {
      const files = e.target.files
      if (files.length === 0) {
        this.pubFrom.cover_img = null
        this.$refs.imgRef.setAttribute('src', imgObj)
      } else {
        this.pubForm.cover_img = files[0]
        // 把图片文件显示到img标签里
        const url = URL.createObjectURL(files[0])
        this.$refs.imgRef.setAttribute('src', url)
      }
      this.$refs.pubFormRef.validateField('cover_img')
    },
    // 表单里点击发布 存为草稿的点击事件
    pubArticleFn(str) {
      this.pubForm.state = str
      this.$refs.pubFormRef.validate(async valid => {
        if (valid) {
          // 都通过
          // 专门为了装文件内容和其他参数的容器
          const fd = new FormData()
          console.log(this.pubForm)
          fd.append('title', this.pubForm.title)
          fd.append('cate_id', this.pubForm.cate_id)
          fd.append('content', this.pubForm.content)
          fd.append('cover_img', this.pubForm.cover_img)
          fd.append('state', this.pubForm.state)
          console.log(fd)
          const { data: res } = await uploadArticleAPI(fd)
          if (res.code !== 0) return this.$message.error('发布文章失败！')
          this.$message.success('发布文章成功！')
          this.pubDialogVisible = false
          this.getArticleListFn()
        } else {
          return false
        }
      })
    },
    // 文章标题点击事件 为了查看详情
    async showDetailFn(artId) {
      this.detailVisible = true
      const res = await getArtDetailAPI(artId)
      this.artDetail = res.data.data
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .btn-pub {
    margin-top: 5px;
  }
}

::v-deep .ql-editor {
  min-height: 300px;
}

.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination {
  margin-top: 15px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;

  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
::v-deep img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
</style>
